package com.xingfei.blog.controller;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.json.ParseException;
import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.common.model.RegisterVo;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.constants.RedisConstants;
import com.xingfei.blog.dto.UserDTO;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.CookieUtil;
import com.xingfei.blog.utils.EMailSenderUtil;
import com.xingfei.blog.utils.TokenCodeUtil;
import com.xingfei.blog.vo.TokenCode;
import com.xingfei.blog.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;

/**
 * Created with IntelliJ IDEA.
 * 注册功能前端控制器
 *
 * @author: chenxingfei
 * @time: 2017/3/12  9:30
 * To change this template use File | Settings | File Templates.
 */
@RequestMapping(value = "/register")
@Controller
public class RegisterController {

    @Autowired
    private RedisClusterUtil redisCluster;
    @Autowired
    private WebUserService webUserService;

    /**
     * 跳转到注册页面
     *
     * @return
     */
    @GetMapping("/toSignUp")
    public ModelAndView toRegister() {
        return new ModelAndView("/register/jianyi-regist");
    }
    /**
     * 跳转到注册页面
     *
     * @return
     */
    @GetMapping("/toRegisterStep2")
    public String toRegisterStep2(String tk_u, Model model) {
        if(StringUtils.isNotBlank(tk_u)){
            model.addAttribute("registerToken",tk_u);
        }
        return "/register/jianyi-regist2";
    }
    /**
     * 跳转到邮箱注册第二步
     *
     * @return
     */
    @GetMapping("/toEmailRegisterStep2")
    public String emailRegisterStep2(String tk_u, Model model) {
        if(StringUtils.isNotBlank(tk_u)){
            //String userINFO = RedisUtil.get(tk_u, 1);
            String userINFO = redisCluster.get(tk_u);
            try {
                UserDTO userDTO = JSON.parse(userINFO, UserDTO.class);
                if(userDTO!=null){
                    model.addAttribute("email",userDTO.getEmail());
                    model.addAttribute("tk_u",tk_u);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return "/register/jianyi-register-email2";
    }

    /**
     * 跳转到邮箱注册页面
     *
     * @return
     */
    @GetMapping("/toEmailRegisterPage")
    public String toEmailRegisterPage() {
        return "/register/jianyi-register-email1";
    }
    /**
     * 跳转到注册成功页面(跳过功能)
     *
     * @return
     */
    @GetMapping("/toRegisterSuccessPage")
    public String toRegisterSuccessPage(String tk_u,Model model) {
        String result = null;
        if(StringUtils.isNotBlank(tk_u)){
            model.addAttribute("tk_u",tk_u);
            result = "/register/jianyi-regist3";
        }else{
            result = "/login/jianyi-login";
        }
        return result;
    }
    /**
     * 跳转到注册成功页面(跳过功能)
     *
     * @return
     */
    @GetMapping("/toEmailRegisterSuccessPage")
    public String toEmailRegisterSuccessPage(String tk_u,Model model,HttpServletRequest request) {
        String result = null;
        if(StringUtils.isNotBlank(tk_u)){
            model.addAttribute("tk_u",tk_u);
            result = "/register/jianyi-register-email5";
        }else{
            result = "/login/jianyi-login";
        }
        return result;
    }

    /**
     * 通用注册接口
     * @param registerVo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/signUp")
    public JsonResult registerStepOne(RegisterVo registerVo, HttpServletRequest request, HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
        if (registerVo != null) {
            UserDTO userDTO = new UserDTO();
            String registerToken = this.webUserService.saveUserAndSaveUserInfo(registerVo, request,userDTO);
            if (StringUtils.isNotBlank(registerToken)) {
                CookieUtil.setCookie(response,"token",registerToken);
                //注册成功
                jsonResult = new JsonResult(registerToken,ErrorConstants.SERVER_SUCCESS, "注册成功！");
            } else {
                jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册信息有误，请重试！");
            }
        }
       return jsonResult;
    }


    /**
     * 注册功能（第二步）<br/>
     * 用户手机号注册第二步<br/>
     * 根据手机号查询用户数据并修改记录<br/>
     *
     * @param registerVo 封装注册对象
     * @return
     */
    @PostMapping(value = "/phoneRegisterStepTwo")
    public String registerStepTwo(RegisterVo registerVo,String au_k,Model model) {
        String result = "/register/error";
        //校验两次密码是否一致
        if (registerVo != null) {
            //调用服务注册数据
            UserVO userVO = new UserVO();
            try {
                UserDTO userDTO = JSON.parse(au_k, UserDTO.class);
                userVO.setEmail(registerVo.getEmail());
                userVO.setId(userDTO.getId());
                userVO.setPhone(userDTO.getPhone());
                userVO.setUsername(registerVo.getUserName());
                Integer integer = this.webUserService.updateUserAndUserInfo(userVO);
                if(integer > 0){
                    //注册成功，跳转至成功页面，放入用户token
                    model.addAttribute("au_k",au_k);
                    result = "/register/jianyi-regist3";
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        return result;
    }

    /**
     * 调用用户服务保存数据
     * @param registerVo
     * @return
     */
    @PostMapping(value = "/toEmailRegisterStepOne")
    @ResponseBody
    public JsonResult toEmailRegisterStepOne(RegisterVo registerVo,HttpServletRequest request,Model model){
        JsonResult jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
        //校验参数
        if (registerVo != null) {
            //调用用户服务
            UserDTO userDTO = new UserDTO();
            String registerToken = this.webUserService.saveUserAndSaveUserInfo(registerVo, request,userDTO);
            if(StringUtils.isNotBlank(registerToken)){
                //发送邮件
                boolean sendEmailResult = EMailSenderUtil.sendActiveEmail(userDTO.getId(), userDTO.getEmail(), registerVo.getUserName());
                //发送邮件成功跳转
                if(sendEmailResult){
                    //注册成功
                    jsonResult = new JsonResult(registerToken,ErrorConstants.SERVER_SUCCESS, "注册成功！");
                }
            }

        }
        return jsonResult;
    }
    /**
     * 邮箱注册第四步
     * @param registerVo
     * @return
     */
    @PostMapping(value = "/toEmailRegisterStepFour")
    @ResponseBody
    public JsonResult toEmailRegisterStepFour(RegisterVo registerVo,HttpServletRequest request,Model model){
        JsonResult jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
        //校验参数
        if (registerVo != null) {
            //调用用户服务
            TokenCode tokenCode = TokenCodeUtil.getTokenCode(registerVo.getToken());
            String userId = tokenCode.getUserId();
            if(StringUtils.isNotBlank(userId)){
                String key = MessageFormat.format(RedisConstants.USER_TOKEN_CODE_KEY, userId);
                //String userInfo = RedisUtil.get(key,1);
                String userInfo = redisCluster.get(key);
                if(StringUtils.isNotBlank(userInfo) && StringUtils.contains(userInfo,":")){
                    String[] userINfo = userInfo.split(":");
                    UserVO userVo = new UserVO();
                    userVo.setId(Long.parseLong(userINfo[0]));
                    userVo.setEmail(userINfo[1]);
                    userVo.setPhone(registerVo.getPhone());
                    String token = this.webUserService.updateUserAndUserInfo4Email(userVo, request);
                    if(StringUtils.isNotBlank(token)){
                        //注册成功
                        jsonResult = new JsonResult(token,ErrorConstants.SERVER_SUCCESS, "注册成功！");
                    }else{
                        //注册失败
                        jsonResult = new JsonResult(token,ErrorConstants.SERVER_ERROR, "注册失败！");
                    }
                }
            }
        }
        return jsonResult;
    }
}
